<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" class="input-with-select" v-model.trim="queryInfo.query" clearable @clear="getUsersList"> <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button> </el-input
        ></el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserFormVisible = true"> 添加用户 </el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userList" border style="width: 100%">
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="option" label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)"></el-button>
            <!-- 删除按钮 -->
            <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(scope.row)"></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="handleRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addUserFormVisible" @close="closeAddForm">
      <!-- 内容主体区域 -->
      <el-form :model="addUserForm" :rules="addrules" ref="addFormRef">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model.trim="addUserForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model.trim="addUserForm.password" autocomplete="off" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model.trim="addUserForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="addUserForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUserFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="editUserVisible" @close="closeEditForm">
      <el-form :model="editUserForm" :rules="editrules" ref="editFormRef">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="editUserForm.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="editUserForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="editUserForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
      <p>当前的用户：{{ userInfo.username }}</p>
      <p>当前的角色：{{ userInfo.role_name }}</p>
      <p>
        分配新角色:
        <el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option v-for="role in rolesList" :key="role.id" :label="role.roleName" :value="role.id"></el-option>
        </el-select>
      </p>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false" clearable="true">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo" clearable="true">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    var checkTel = (rule, value, callback) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (!reg.test(value)) {
        return callback(new Error('请输入正确的电话号码'))
      } else {
        return callback()
      }
    }
    return {
      userList: [],
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      formLabelWidth: '120px',
      addUserFormVisible: false,
      addUserForm: {
        username: 'admin11',
        password: 'admin11',
        email: 'admin11@126.com',
        mobile: '18616018802'
      },
      addrules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur', type: 'email' }],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkTel, trigger: 'blur' }
        ]
      },
      editUserForm: {},
      editUserVisible: false,
      editrules: {
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur', type: 'email' }],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkTel, trigger: 'blur' }
        ]
      },
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      // 已选中的角色Id值
      selectedRoleId: ''
    }
  },
  methods: {
    get() {
      console.log('a')
    },
    // 获取用户列表
    async getUsersList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      console.log(res)
      if (res.meta.status != 200) return
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 修改用户信息
    async handleEdit(row) {
      const { data: res } = await this.$http.get(`users/${row.id}`)
      if (res.meta.status != 200) return
      this.editUserForm = res.data
      this.editUserVisible = true
      console.log(this.editUserForm)
    },
    editUser() {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(`users/${this.editUserForm.id}`, { email: this.editUserForm.email, mobile: this.editUserForm.mobile })
          if (res.meta.status == 200) {
            this.editUserVisible = false
            this.$message.success(res.meta.msg)
            this.getUsersList()
          } else this.$message.error(res.meta.msg)
        } else return
      })
    },
    closeEditForm() {
      this.$refs.editFormRef.resetFields()
    },
    // 删除用户
    async handleDelete(row) {
      const confirmresult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，则打印字符串confirm
      // 如果用户取消删除，则打印字符串cancel
      if (confirmresult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + row.id)
      if (res.meta.status === 400) {
        return this.$message.error('admin用户不能删除')
      }
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }

      this.$message.success('删除用户成功')
      console.log(this.userList)
      if (this.userList.length == 1) {
        this.queryInfo.pagenum = this.queryInfo.pagenum === 1 ? 1 : this.queryInfo.pagenum - 1
      }
      console.log(this.queryInfo.pagenum)
      this.getUsersList()
    },
    // 修改用户权限
    handleRole(index, row) {},

    // 一页几条数据
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getUsersList()
    },
    // 当前处于第几页
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getUsersList()
    },

    // 修改用户状态
    async changeState(user) {
      const { data: res } = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
      if (res.meta.status != 200) {
        user.mg_state = !user.mg_state
        return this.$message.error('更改用户状态失败')
      }
      this.$message.success('更改用户状态成功')
    },
    closeAddForm() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮，添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('/users', this.addUserForm)
          if (res.meta.status == 201) {
            this.addUserFormVisible = false
            this.$message.success(res.meta.msg)
            this.getUsersList()
          } else this.$message.error(res.meta.msg)
        } else return
      })
    },
    // 打开修改用户角色表单
    async handleRole(role) {
      console.log(role)
      this.userInfo = role
      this.setRoleDialogVisible = true
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolesList = res.data
    },
    // 点击按钮，分配角色
    async saveRoleInfo() {
      console.log(this.selectedRoleId)
      if (!this.selectedRoleId) return this.$message.error('请选择要分配的角色')
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('更新角色成功！')
      this.getUsersList()
      this.setRoleDialogVisible = false
    },
    setRoleDialogClosed() {
      ;(this.userInfo = {}), (this.selectedRoleId = ''), (this.setRoleDialogVisible = false)
    }
  },
  created() {
    this.getUsersList()
  }
}
</script>

<style lang="less" scoped></style>
